package com.sdau.repairmaster.UIFile.fragment;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterViewAnimator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import com.sdau.repairmaster.R;
import com.sdau.repairmaster.UIFile.HomeActivity;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.cache.FaultHidingSink;

import static android.app.Activity.RESULT_OK;
import static android.os.Build.VERSION.SDK_INT;

public class FirstFragment extends Fragment implements View.OnClickListener, TextWatcher {
    private final int FAILURE_CODE=1001;//失败
    private final int SUCCESS_CODE=1000;//成功
    private String repairType;
    private String repairDescribe;
    private String repairName;
    private String repairTel;
    private String repairAddress;

    final String URL_Picture = "http://10.0.2.2:8080/RepairAdmin/uploadServlet";


    //定义控件
    private EditText etRepairType;
    private EditText etRepairAddress;
    private EditText etDescribe;
    private EditText etPicture;
    private EditText etName;
    private EditText etTel;

    private ImageView ivRepairTypeDel;
    private ImageView ivRepairAddressDel;
    private ImageView ivRepairDescribeDel;
    private ImageView ivRepairPictureDel;
    private ImageView ivRepairNameDel;
    private ImageView ivRepairTelDel;
    private Button btnRepairSubmit;

    private ImageView ivRepairPicture = null;//展示相关报修图片

    private ImageButton btnGetPictureC;
    private ImageButton btnGetPictureA;

    //和获取照片相关的变量
    public static final int TAKE_PHOTO=1;
    private Uri imageUri;

    private String picturePath = null;


    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_first, container, false);
        initView(view);
        initListener();
        IsEdit();
        return view;
    }



    /*
           看数据库中是否存在该账户以及密码是否正确
        */
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SUCCESS_CODE://成功
                    String data= (String) msg.obj;
                    //Log.d("MIN",data);
                    if("true".equals(data.trim()))// loginSuccess();
                    {
                        Toast.makeText(getContext(), "提交成功！", Toast.LENGTH_SHORT).show();
                        System.out.println("Trans the picture is  Ok");
                        startActivity(new Intent(getContext(),HomeActivity.class));
                    }
                    else//  loginFaile();
                        System.out.println("Open Failed");
                    break;
                case FAILURE_CODE://失败
                    /// loginFaile();
                    Toast.makeText(getContext(), "网络异常", Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };

    private Handler handler1 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SUCCESS_CODE://成功
                    String data= (String) msg.obj;

                    if("true".equals(data.trim())){
                        System.out.println("data : " +data);
                        Log.d("sql state: ",data);
                        Log.d("TAG","I'm Ok");
                        try {
                            uploadImage(URL_Picture,picturePath);
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    else{
                        System.out.println("data: " + data);
                        Log.d("sql state: ",data);
                        Log.d("TAG","I'm not Ok");
                    }

                    break;
                case FAILURE_CODE://失败
                    //loginFaile();
                    Toast.makeText(getContext(),"网络异常",Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };

    public FirstFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param
     * @param
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FirstFragment newInstance() {
        FirstFragment fragment = new FirstFragment();

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    //初始化控件
    public void initView(View view){

        etRepairType = view.findViewById(R.id.et_repair_type);
        etRepairAddress = view.findViewById(R.id.et_repair_address);
        etDescribe = view.findViewById(R.id.et_repair_describe);
        etName = view.findViewById(R.id.et_repair_name);
        etTel = view.findViewById(R.id.et_repair_tel);

        ivRepairTypeDel = view.findViewById(R.id.iv_repair_type_del);
        ivRepairAddressDel = view.findViewById(R.id.iv_repair_address_del);
        ivRepairDescribeDel = view.findViewById(R.id.iv_repair_describe_del);
        ivRepairNameDel = view.findViewById(R.id.iv_repair_name_del);
        ivRepairTelDel = view.findViewById(R.id.iv_repair_tel_del);

        ivRepairPicture = view.findViewById(R.id.show_repairPicture);

        btnRepairSubmit = view.findViewById(R.id.bt_repair_submit);


        //上传图片
        btnGetPictureC = view.findViewById(R.id.bt_repair_getPicture_c);
        btnGetPictureA = view.findViewById(R.id.bt_repair_getPicture_a);
    }

    //设置监听器
    public void initListener(){
        etRepairType.setOnClickListener(FirstFragment.this);
        etRepairAddress.setOnClickListener(FirstFragment.this);
        btnGetPictureC.setOnClickListener(FirstFragment.this);
        btnGetPictureA.setOnClickListener(FirstFragment.this);

        etName.addTextChangedListener(FirstFragment.this);
        etTel.addTextChangedListener(FirstFragment.this);
        ivRepairNameDel.setOnClickListener(FirstFragment.this);

        btnRepairSubmit.setOnClickListener(FirstFragment.this);
    }
    //设置是否可编辑
    public void IsEdit(){

        etRepairType.setFocusableInTouchMode(false);
       // etRepairAddress.setFocusableInTouchMode(false);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.et_repair_type:
                AlertDialog.Builder builderType = new AlertDialog.Builder(getActivity());
                final String[] types = {"多媒体","桌椅","灯泡","门窗","其它"};
                builderType.setTitle("请选择类型")
                        .setSingleChoiceItems(types, -1, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                etRepairType.setText(types[i]);
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).show();
                break;
            case R.id.et_repair_address:
//                AlertDialog.Builder builderAddress = new AlertDialog.Builder(getActivity());
//                final String[] address = {"java","python","c++","1","2","3","4","5","6","7","8","9","10"};
//                builderAddress.setTitle("请选择位置")
//                        .setSingleChoiceItems(address, -1, new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialogInterface, int i) {
//                                etRepairType.setText(address[i]);
//                            }
//                        })
//                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialogInterface, int i) {
//
//                            }
//                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//
//                    }
//                }).show();


                break;
            //从相机拍照
            case R.id.bt_repair_getPicture_c:
                File outputImage=new File(getActivity().getExternalCacheDir(),"output_image.jpg");//用于存放摄像头拍摄的照片
                try{
                    if (outputImage.exists()){
                        outputImage.delete();
                    }
                    outputImage.createNewFile();
                }catch (IOException e){
                    e.printStackTrace();
                }
                if (SDK_INT>=24){//根据android的版本对URI执行操作
                    imageUri= FileProvider.getUriForFile(getActivity(),"com.sdau.repairmaster.UIFile.fragment.fileprovider",outputImage);}
                else{
                    imageUri=Uri.fromFile(outputImage);
                }
                Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");//系统会找到能够找到能响应这个intent程序去执行
                intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                startActivityForResult(intent,TAKE_PHOTO);

                break;


            //从相册获取图片
            case R.id.bt_repair_getPicture_a:
                if (ContextCompat.checkSelfPermission(getContext(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.
                        PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(getActivity(),
                            new String[]{ Manifest.permission. WRITE_EXTERNAL_STORAGE }, 1);
                } else {
                    openAlbum();
                }

                break;
            case R.id.bt_repair_submit:
                getSubmit();
                break;
            default :
                break;

        }

    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, 2); // 打开相册
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){//如果拍照成功，则会将照片显示在容器中
        switch (requestCode){
            case TAKE_PHOTO:
                if(resultCode==RESULT_OK){
                    try{
                        Bitmap bitmap= BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri));
                        btnGetPictureC.setVisibility(View.GONE);
                        btnGetPictureA.setVisibility(View.GONE);
                        ivRepairPicture.setImageBitmap(bitmap);
                        openAlbum();
                    }catch (FileNotFoundException e){
                        e.printStackTrace();
                    }
                }
                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    btnGetPictureC.setVisibility(View.GONE);
                    btnGetPictureA.setVisibility(View.GONE);
                    // 判断手机系统版本号
                    if (SDK_INT >= 19) {
                        // 4.4及以上系统使用这个方法处理图片
                        handleImageOnKitKat(data);
                    } else {
                        // 4.4以下系统使用这个方法处理图片
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
        }
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        Log.d("TAG", "handleImageOnKitKat: uri is " + uri);
        if (DocumentsContract.isDocumentUri(getContext(), uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        picturePath = imagePath;
        displayImage(imagePath); // 根据图片路径显示图片
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }


    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContext().getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            ivRepairPicture.setImageBitmap(bitmap);
        } else {
            Toast.makeText(getContext(), "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }
    //判断清除按钮是否可见
    @Override
    public void afterTextChanged(Editable editable) {
        String name = etName.getText().toString().trim();
        String tel = etTel.getText().toString().trim();

        if (name.length() > 0)  {
            ivRepairNameDel.setVisibility(View.VISIBLE);
        }else{
            ivRepairNameDel.setVisibility(View.INVISIBLE);
        }
        if (tel.length() > 0)  {
            ivRepairTelDel.setVisibility(View.VISIBLE);
        }else{
            ivRepairTelDel.setVisibility(View.INVISIBLE);
        }
    }

    public void getSubmit(){
        repairType = etRepairType.getText().toString();
        repairDescribe = etDescribe.getText().toString();
        repairName = etName.getText().toString();
        repairTel = etTel.getText().toString();
        repairAddress = etRepairAddress.getText().toString();

        if(ivRepairPicture != null && !Is_Null(repairType) && !Is_Null(repairDescribe) &&
                !Is_Null(repairName) && !Is_Null(repairTel) && !Is_Null(repairAddress) &&
                !Is_Null(picturePath)){
            Log.d("TAG","START");
            transString(repairType, repairDescribe, repairAddress, repairName, repairTel,picturePath);
        }

    }

    public boolean Is_Null(String str){
        return TextUtils.isEmpty(str);
    }

    private void transString(final String repairType, final  String repairDescribe,final  String repairAddress,
                            final String repairName, final  String repairTel,final String picturePath) {

        Adapter();
        Log.d("TAG","Continue");
        final String URL_login = "http://10.0.2.2:8080/RepairAdmin/userServlet";
        final Message message= Message.obtain();


        OkHttpClient okHttpClient  = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10,TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();



        RequestBody requestBody = new FormBody.Builder()
                .add("repairType", repairType)
                .add("repairDescribe",repairDescribe)
                .add("repairAddress",repairAddress)
                .add("repairName",repairName)
                .add("repairTel",repairTel)
                .add("picturePath",picturePath)
                .add("flag","addRepairInfo")
                .build();

        System.out.println(repairType + " " + repairTel + " " + repairAddress + " " + repairDescribe + " " +
                picturePath);;


        final OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(URL_login)
                .post(requestBody)
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                message.what=FAILURE_CODE;
                message.obj=e.getMessage();//失败的信息
                System.out.println("Trans Failed");
                handler1.sendMessage(message);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String data=response.body().string();
                message.what=SUCCESS_CODE;
                message.obj=data;
                Log.d("TAG","Result : " + data);
                handler1.sendMessage(message);

            }
        });



    }
    /**
     *
     * @param url --地址
     * @param imagePath -- 图片地址
     * @throws IOException
     * @throws JSONException
     */
    public  void uploadImage(final String url, final String imagePath) throws IOException, JSONException {

        final Message message=Message.obtain();

        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                //Log.d("imagePath", imagePath);-- --> storage/emulated/0/DCIM/70562262_p0.png
                File file = new File(imagePath);
                RequestBody image = RequestBody.create(MediaType.parse("image/png"), file);

                RequestBody requestBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("file", imagePath, image)
                        .build();
                Request request = new Request.Builder()
                        .url(url)
                        .post(requestBody)
                        .build();

                final OkHttpClient client = new OkHttpClient();

                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        message.what=FAILURE_CODE;
                        message.obj=e.getMessage();//失败的信息
                        handler.sendMessage(message);
                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        String data=response.body().string();
                        message.what=SUCCESS_CODE;
                        message.obj=data;
                        handler.sendMessage(message);

                    }
                });
                /*
                Response response = null;
                try {
                    response = okHttpClient.newCall(request).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {

                    String str = response.body().string();
                    Log.d("Str: ",str)  ;
                    message.what= SUCCESS_CODE;
                    message.obj=str;
                    handler.sendMessage(message);
                    // JSONObject jsonObject = new JSONObject(str);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                //return jsonObject.optString("image");

                 */
            }
        }).start();

    }

    public void Adapter(){

        if (SDK_INT < Build.VERSION_CODES.P) {
            return;
        }
        try {
            Method forName = Class.class.getDeclaredMethod("forName", String.class);
            Method getDeclaredMethod = Class.class.getDeclaredMethod("getDeclaredMethod", String.class, Class[].class);
            Class<?> vmRuntimeClass = (Class<?>) forName.invoke(null, "dalvik.system.VMRuntime");
            Method getRuntime = (Method) getDeclaredMethod.invoke(vmRuntimeClass, "getRuntime", null);
            Method setHiddenApiExemptions = (Method) getDeclaredMethod.invoke(vmRuntimeClass, "setHiddenApiExemptions", new Class[]{String[].class});
            Object sVmRuntime = getRuntime.invoke(null);
            setHiddenApiExemptions.invoke(sVmRuntime, new Object[]{new String[]{"L"}});
        } catch (Throwable e) {
            Log.e("[error]", "reflect bootstrap failed:", e);
        }
    }


}



